<template>
  <div v-loading="loading" class="order_early_warning" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addData"> 添加预警 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="name"
          placeholder="区间值搜索"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table_container">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="tableData"
        height="100%"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="40" fixed="left" :align="'center'" />
        <el-table-column
          show-overflow-tooltip
          type="index"
          :index="indexMethod"
          label="序号"
          width="50"
          fixed="left"
          :align="'center'"
        />
        <el-table-column show-overflow-tooltip prop="max,min" label="预警名称" min-width="200">
          <template #default="item">
            <span>{{ item.row.min }} ~ {{ item.row.max }}天未处理</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="color" label="预警颜色" width="100" />
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="!scope.row.status">启用</HStatus>
              <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="90">
          <template #default="scope">
            <h-space>
              <HLink @click="editData(scope.row.id)">编辑</HLink>
              <HLink type="error" @click="handleDelOrderEarlyWarning(scope.row)">删除</HLink>
            </h-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList(false)"
      />
    </div>

    <!-- 添加/编辑  预警弹窗 -->
    <h-dialog v-model="addDialog" :title="dialogTitle" :loading="dialogLoading">
      <el-form
        ref="formRef"
        class="modal_form_content"
        label-position="top"
        inline-message
        :rules="rules"
        :model="form"
      >
        <el-form-item label="预警区间" prop="min">
          <div class="early_warning_range">
            <el-input
              v-model.trim="form.min"
              clearable
              maxlength="6"
              placeholder="最小值"
              @input="() => (form.min = Number(form.min.toString().replace(/[^\d]/g, '')))"
            />
            <span class="tip">~</span>
            <el-input
              v-model.trim="form.max"
              clearable
              maxlength="6"
              placeholder="最大值"
              @input="() => (form.max = Number(form.max.toString().replace(/[^\d]/g, '')))"
            />
          </div>
        </el-form-item>
        <div class="same_line">
          <el-form-item label="预警状态" class="same_line">
            <el-radio-group v-model="form.status">
              <el-radio :value="false">启用</el-radio>
              <el-radio :value="true">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="预警颜色" class="same_line">
            <el-color-picker v-model="form.color" />
          </el-form-item>
        </div>
      </el-form>

      <template #footer>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="addDialog = false">取消</HButton>
      </template>
    </h-dialog>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, reactive } from 'vue'
  import { Search, Warning, Delete, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, TableInstance } from 'element-plus'
  import { warnSave, warnGetList, warnGetDetail, warnDisable, warnDelete } from '@/api/basic'
  import { OrderEarlyWarning } from './types'

  const handleDelOrderEarlyWarning = (orderEarlyWarning: OrderEarlyWarning) => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      tableDom.value.toggleRowSelection(orderEarlyWarning, true)
      changeStatus(3)
    }
  }

  const loading = ref(false)
  const addDialog = ref(false)
  const name = ref('') // 关键词

  const tableData = ref([]) // 列表数据
  const tableDom = ref<TableInstance | null>(null) // 列表dom

  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目

  const formRef = ref<FormInstance>() // 表单元素
  const dialogTitle = ref('')
  const dialogLoading = ref(false)

  // 表单数据
  const form = reactive({
    color: '#f56c6c',
    id: null,
    max: 4,
    min: 2,
    status: false,
    weight: 1,
  })

  // 验证规则
  const rules = reactive({
    min: [
      { required: true, message: '请输入最小值', trigger: ['blur', 'change'] },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: ['blur', 'change'],
      },
      {
        validator: (rule, value, callback) => {
          if (!form.max) {
            callback(new Error('请输入最大值'))
            return
          }

          const regexp = /^[+]{0,1}(\d+)$/g
          if (!regexp.test(form.max.toString())) {
            callback(new Error('格式错误'))
            return
          }

          if (form.min > form.max) {
            callback(new Error('最小值不能大于最大值'))
            return
          }

          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
    weight: [
      { required: true, message: '请输入预警权重', trigger: 'blur' },
      {
        pattern: /^[+]{0,1}(\d+)$/g,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
  })

  // 列表序号
  const indexMethod = (index: number) => {
    return index + 1
  }

  // 获取分页数据
  const getPageData = (val) => {
    if (val) pagination.value.setPage()
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async (val = true) => {
    loading.value = true
    await warnGetList(getPageData(val)).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 添加预警
  const addData = () => {
    dialogTitle.value = '添加预警'
    addDialog.value = true
    form.color = '#f56c6c'
    form.id = null
    form.max = 4
    form.min = 2
    form.status = false
    form.weight = 1
  }

  // 编辑预警
  const editData = async (id) => {
    addDialog.value = true
    dialogLoading.value = true
    dialogTitle.value = '编辑预警'
    await warnGetDetail(id).then((res) => {
      form.color = res.data.data.row.color
      form.id = res.data.data.row.id
      form.max = res.data.data.row.max
      form.min = res.data.data.row.min
      form.status = res.data.data.row.status
      form.weight = res.data.data.row.weight
    })
    dialogLoading.value = false
  }

  // 保存方法
  const saveDataMethod = (method, data) => {
    dialogLoading.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        addDialog.value = false
        dialogLoading.value = false
        getList()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'warning',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        dialogLoading.value = false
        return
      }
    })
  }

  // 保存数据
  const saveData = (formEl: FormInstance | undefined) => {
    formEl
      .validate()
      .then(() => {
        if (form.max < form.min) {
          ElMessage({
            message: '最大值不能小于最小值',
            type: 'warning',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          return
        }
        saveDataMethod(warnSave, form)
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起eslint的报错
      })
  }

  // 修改状态方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的预警`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}选中的预警?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (dialog != '') {
            addDialog.value = false
          }
        })
      }
      selecttion.value = []
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeStatus = (n) => {
    if (n == 1) {
      changeMethod('启用', warnDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', warnDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', warnDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', warnDelete, [form.id], 3, addDialog)
    }
  }

  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';

  .early_warning_range {
    display: flex;
    column-gap: 5px;
    width: 100%;
    height: 28px;
  }
</style>
